﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ERP.WebUI
{
    public class RoleModulePermissionRepository 
    {
        EFDbContext db = new EFDbContext();
        public IQueryable<RoleModulePermission> RoleModulePermissions
        {
            get 
            {
                    return db.RoleModulePermissions;
            }
        }

        public OperationResult SetRoleModulePermission(int roleId, IEnumerable<RoleModulePermissionModel> addModulePermissionList, IEnumerable<RoleModulePermissionModel> removeModulePermissionList)
        {
            //逻辑删除
            if (removeModulePermissionList.Count() > 0)
            {
                foreach (var rmp in removeModulePermissionList)
                {
                    var updateEntity = RoleModulePermissions.FirstOrDefault(t => t.RoleId == roleId && t.ModuleId == rmp.ModuleId && t.PermissionId == rmp.PermissionId && t.IsDeleted == false);
                    if (updateEntity != null)
                    {
                        updateEntity.IsDeleted = true;
                        db.Set<RoleModulePermission>().Attach(updateEntity);
                        db.Entry<RoleModulePermission>(updateEntity).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            //插入 & 更新
            if (addModulePermissionList.Count() > 0)
            {
                foreach (var amp in addModulePermissionList)
                {
                    var updateEntity = RoleModulePermissions.FirstOrDefault(t => t.RoleId == roleId && t.ModuleId == amp.ModuleId && t.PermissionId == amp.PermissionId && t.IsDeleted == true);
                    if (updateEntity != null)
                    {
                        updateEntity.IsDeleted = false;
                        db.Set<RoleModulePermission>().Attach(updateEntity);
                        db.Entry<RoleModulePermission>(updateEntity).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        var addEntity = new RoleModulePermission
                        {
                            RoleId = roleId,
                            ModuleId = amp.ModuleId,
                            PermissionId = amp.PermissionId
                        };
                        db.Entry<RoleModulePermission>(addEntity).State = EntityState.Added;
                        db.SaveChanges();
                    }
                }
            }

            return new OperationResult(OperationResultType.Success, "授权成功");
        }       


        public void Dispose()
        {
            db.Dispose();
        }
    }
}